package com.atguigu.servlet;

import com.atguigu.bean.User;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Date:2020/9/18
 * Author:ybc
 * Description:
 */
public class TestJsonServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        User user1 = new User(1001,"admin","123456",23,"男");
        User user2 = new User(1002,"admin","123456",23,"男");
        User user3 = new User(1003,"admin","123456",23,"男");
        /*List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);*/
        Map<String, User> map = new HashMap<>();
        map.put("1001", user1);
        map.put("1002", user2);
        map.put("1003", user3);
        //需要先将user转换为json格式
        Gson gson = new Gson();
        String json = gson.toJson(map);
        response.getWriter().print(json);
    }
}
